﻿using Dora.Orm.SqlSugarCore.UnitOfWork;
using Dora.Services.AdminUser.Dto.QueryDto;
using Dora.Services.AdminUser.Dto.ViewDto;
using Dora.Services.AdminUser.Entities;
using SqlSugar;
using Surging.Core.Common;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Dora.Services.AdminUser.Repository.Repositorys
{/// <summary>
 /// 供应商用户表仓储层
 /// </summary>
    public class SrmUserRepository : SqlSugarRepository<SrmUserEntity, Guid>
    {
        private ISugarUnitOfWork _unitOfWork;
        public SrmUserRepository(ISugarUnitOfWork unitOfWork) : base(unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageDataList<SrmUserListDto>> GetPageList(SrmUserQueryDto input)
        {
            var pagePredict = _unitOfWork.QueryClient.Queryable<SrmUserEntity>()
                .Where(it => it.IsDeleted == 0)
                .WhereIF(input.SupplierId.HasValue, it => it.SupplierId == input.SupplierId)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Keywords), it => it.Mobile.Contains(input.Keywords.Trim()) || it.UserName.Contains(input.Keywords.Trim())
                || it.RealName.Contains(input.Keywords.Trim()) || it.Email.Contains(input.Keywords.Trim()))
                ;
            var totalCount = await pagePredict.CountAsync();
            var pageList = await pagePredict.OrderBy(it => it.CreatedTime, OrderByType.Desc).Select((it) => new SrmUserListDto
                {
                    Id = it.Id,
                    HxUserName = it.HxUserName,
                    UserName = it.UserName,
                    Mobile = it.Mobile,
                    MobileIsVerified = it.MobileIsVerified,
                    Email = it.Email,
                    EmailIsVerified = it.EmailIsVerified,
                    RealName = it.RealName,
                    Sex = it.Sex,
                    Sort = it.Sort,
                    IsDisabled = it.IsDisabled,
                    IsFrozen = it.IsFrozen,
                    IsSuperAdmin = it.IsSuperAdmin,
                    Avatar = it.Avatar,
                    Remark = it.Remark,
                    SupplierId = it.SupplierId
                }).ToPageListAsync(input.PageIndex, input.PageSize);
            var page = new PageDataList<SrmUserListDto>(totalCount, pageList, input.PageIndex, input.PageSize);
            return page;
        }

        /// <summary>
        /// 根据用户名获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<SrmUserEntity> GetByUserName(string userName)
        {
            return await _unitOfWork.QueryClient.Queryable<SrmUserEntity>().FirstAsync(item => item.UserName == userName);
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public new async Task<bool> Delete(Guid id)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<SrmUserEntity>()
                .SetColumns(it => new SrmUserEntity() { IsDeleted = 1, UpdatedTime = DateTime.Now })
                .Where(it => it.Id == id).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 根据手机号获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<SrmUserEntity> GetByMobile(string mobile)
        {
            return await _unitOfWork.QueryClient.Queryable<SrmUserEntity>().FirstAsync(item => item.Mobile == mobile && item.IsDeleted == 0);
        }

        /// <summary>
        /// 根据验证后的手机号获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<SrmUserEntity> GetByVerifiedMobile(string mobile)
        {
            return await _unitOfWork.QueryClient.Queryable<SrmUserEntity>().FirstAsync(item => item.Mobile == mobile && item.MobileIsVerified == 1 && item.IsDeleted == 0);
        }

        /// <summary>
        /// 根据手机号获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<SrmUserEntity> GetByEmail(string email)
        {
            return await _unitOfWork.QueryClient.Queryable<SrmUserEntity>().FirstAsync(item => item.Email == email);
        }

        /// <summary>
        /// 根据验证后的手机号获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<SrmUserEntity> GetByVerifiedEmail(string email)
        {
            return await _unitOfWork.QueryClient.Queryable<SrmUserEntity>().FirstAsync(item => item.Email == email && item.EmailIsVerified == 1);
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdatePassword(SrmUserEntity entity)
        {
            //var result = await _unitOfWork.ModifyClient.Updateable(entity).UpdateColumns(it => new { it.Password, it.UpdatedTime }).ExecuteCommandAsync() > 0;
            var result = await _unitOfWork.ModifyClient.Updateable<SrmUserEntity>()
                .SetColumns(it => new SrmUserEntity() { Password = entity.Password, UpdatedTime = DateTime.Now })
                .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
            return result;
        }
        
        /// <summary>
        /// 禁用/启用用户
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> IsDisabled(SrmUserEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<SrmUserEntity>()
                .SetColumns(it => new SrmUserEntity() { IsDisabled = entity.IsDisabled, UpdatedTime = entity.UpdatedTime, UpdatedUserId = entity.UpdatedUserId, UpdatedUserName = entity.UpdatedUserName })
                .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 冻结/解冻用户
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> IsFrozen(SrmUserEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<SrmUserEntity>()
                .SetColumns(it => new SrmUserEntity() { IsFrozen = entity.IsFrozen, UpdatedTime = entity.UpdatedTime, UpdatedUserId = entity.UpdatedUserId, UpdatedUserName = entity.UpdatedUserName })
                .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
            return result;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public new async Task<bool> Update(SrmUserEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable(entity).UpdateColumns(it => new
            {
                //it.Id,
                //it.UserName,
                //it.Password,
                //it.PasswordSalt,
                it.Mobile,
                //it.MobileIsVerified,
                it.Email,
                //it.EmailIsVerified,
                it.RealName,
                it.Sex,
                it.IDCardNO,
                it.Sort,
                //it.IsDisabled,
                //it.IsFrozen,
                //it.IsSuperAdmin,
                it.Avatar,
                it.Remark,
                //it.IsDeleted,
                //it.CreatedUserId,
                //it.CreatedUserName,
                //it.CreatedTime,
                it.UpdatedUserId,
                it.UpdatedUserName,
                it.UpdatedTime,
            }).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 验证后的手机号是否存在
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ExistVerifiedMobile(string mobile, Guid id)
        {
            return await _unitOfWork.QueryClient.Queryable<SrmUserEntity>().Where(it => it.Mobile == mobile && it.MobileIsVerified == 1 && it.IsDeleted == 0 && it.Id != id).CountAsync() > 0;
        }

        /// <summary>
        /// 修改用户基本信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateBaseInfo(SrmUserEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<SrmUserEntity>()
                .SetColumns(it => new SrmUserEntity() { Avatar = entity.Avatar, Sex = entity.Sex, Phone = entity.Phone, Email = entity.Email, QQAccount = entity.QQAccount, WxAccount = entity.WxAccount, PersonalNote = entity.PersonalNote, UpdatedTime = DateTime.Now, UpdatedUserId = entity.UpdatedUserId, UpdatedUserName = entity.UpdatedUserName })
                .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 修改用户基本信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateMobile(SrmUserEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<SrmUserEntity>()
                .SetColumns(it => new SrmUserEntity() { Mobile = entity.Mobile, UpdatedTime = DateTime.Now })
                .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 修改用户的供应商信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="supplierId"></param>
        /// <returns></returns>
        public async Task<bool> UpdateSupplierId(Guid id, int supplierId)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<SrmUserEntity>()
                .SetColumns(it => new SrmUserEntity() { SupplierId = supplierId, UpdatedTime = DateTime.Now })
                .Where(it => it.Id == id).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 更新环信Id
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateHxUserName(SrmUserEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable(entity)
                .UpdateColumns(it => new { it.HxUserName })
                .ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 获取某个供应商下的所有用户
        /// </summary>
        /// <param name="supplierId">供应商Id</param>
        /// <returns></returns>
        public async Task<List<SrmUserListDto>> GetListBySupplierIdButOne(int supplierId, Guid notInUserId)
        {
            var ressult =await _unitOfWork.QueryClient.Queryable<SrmUserEntity>()
                .Where(it => it.IsDeleted == 0)
                .Where(it => it.SupplierId == supplierId)
                .Where(it => it.Id != notInUserId)
                .Select((it) => new SrmUserListDto
                {
                    Id = it.Id,
                    HxUserName = it.HxUserName,
                    UserName = it.UserName,
                    Mobile = it.Mobile,
                    MobileIsVerified = it.MobileIsVerified,
                    Email = it.Email,
                    EmailIsVerified = it.EmailIsVerified,
                    RealName = it.RealName,
                    Sex = it.Sex,
                    Sort = it.Sort,
                    IsDisabled = it.IsDisabled,
                    IsFrozen = it.IsFrozen,
                    IsSuperAdmin = it.IsSuperAdmin,
                    Avatar = it.Avatar,
                    Remark = it.Remark,
                    SupplierId = it.SupplierId
                }).OrderBy(it => it.Id, OrderByType.Desc).ToListAsync();
            return ressult;
        }


        /// <summary>
        /// 获取某个供应商下的管理员用户
        /// </summary>
        /// <param name="supplierId"></param>
        /// <returns></returns>
        public async Task<List<SrmUserListDto>> GetSrmAdminUserListBySupplierId(int supplierId,string roleNo)
        {
            var ressult = await _unitOfWork.QueryClient.Queryable<SrmUserEntity, SrmUserRoleMapEntity, RoleEntity>((user,srole,role)=>new object[] {
                JoinType.Inner,user.Id==srole.UserId &&user.IsDeleted==0,
                 JoinType.Inner,srole.RoleId==role.Id &&role.IsDeleted==0,
            }).Where((user, srole, role) => user.SupplierId== supplierId).WhereIF(!string.IsNullOrEmpty(roleNo), (user, srole, role) => role.RoleNO== roleNo)
            .Select((user, srole, role) => new SrmUserListDto
            {
                Id = user.Id,
                HxUserName = user.HxUserName,
                UserName = user.UserName,
                Mobile = user.Mobile,
                MobileIsVerified = user.MobileIsVerified,
                Email = user.Email,
                EmailIsVerified = user.EmailIsVerified,
                RealName = user.RealName,
                Sex = user.Sex,
                Sort = user.Sort,
                IsDisabled = user.IsDisabled,
                IsFrozen = user.IsFrozen,
                IsSuperAdmin = user.IsSuperAdmin,
                Avatar = user.Avatar,
                Remark = user.Remark,
                SupplierId = user.SupplierId
            }).ToListAsync();

            return ressult;
        }

    }
}
